#include "maker_base.h"
// uint8_t tap1[] = {0x2a, 0xab, 0x43, 0xf6, 0x03, 0xb4};
// uint8_t tap0[] = {0xbe, 0x26, 0x55, 0xa5, 0xce, 0x34};
int main()
{
    int send_log_count = 0;
    int recv_log_count = 0;
    // 选择网卡接口名
    INFO_PRINT("please enter tap interface name (tap0/tap1):");
    char tap_name[5] = {0};
    int read_count = read(0, tap_name, 5);
    tap_name[4] = 0;
    INFO_PRINT("tap interface name: %s", tap_name);
    // 打开tap[0,1]网卡接口
    int fd = open("/dev/net/tun", O_RDWR);
    struct ifreq ifr;
    memset(&ifr, 0, sizeof(struct ifreq));
    strncpy(ifr.ifr_ifrn.ifrn_name, tap_name, sizeof(tap_name));
    ifr.ifr_ifru.ifru_flags = IFF_TAP | IFF_NO_PI;
    if (ioctl(fd, TUNSETIFF, &ifr) != 0)
    {
        perror(strerror(errno));
        exit(errno);
    };
    if (!strcmp(tap_name, "tap1"))
    {
        uint8_t sender_hw_a[6] = {0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f};
        uint8_t target_hw_a[6] = {0xff, 0xff, 0xff, 0xff, 0xff, 0xff};
        uint8_t sender_p_a[4] = {192, 168, 2, 252};
        uint8_t target_p_a[4] = {192, 168, 2, 1};
        uint8_t data[18] = "helloworld1234567";
        struct arp_pck pck = arp_maker_with_fill_data(sender_hw_a, sender_p_a, target_hw_a, target_p_a, data);
        while (1)
        {
            /* code */
            int pck_len = sizeof(struct arp_pck);
            int need_write = pck_len;
            int write_count = 0;
            void *p_arp_pck = &pck;
            do
            {
                write_count += write(fd, p_arp_pck + write_count, need_write - write_count);
                /* code */
            } while (write_count != need_write);

            DEBUG_PRINT("sender_log %d: sizeof(struct arp_pck) %zd", send_log_count, sizeof(struct arp_pck));
            DEBUG_PRINT("sender_log %d: write_count %d", send_log_count, write_count);
            send_log_count++;
            sleep(1);
        }
    }
    else if (!strcmp(tap_name, "tap0"))
    {
        while (1)
        {
            sleep(1);
            /* code */
            int max_pck_size = 1500 + sizeof(struct ether_header);
            unsigned char buf[1500 + sizeof(struct ether_header)] = {0};
            int read_count = read(fd, buf, max_pck_size);
            DEBUG_PRINT("recv_log %d: read pck read_count:%d", recv_log_count, read_count);
            DEBUG_PRINT("recv_log %d: type: %02x%02x", recv_log_count, buf[12], buf[13]);
            if (buf[12] == 0x08 && buf[13] == 0x06)
            {
                DEBUG_PRINT("recv_log %d: pck is arp", recv_log_count);
                struct arp_pck pck;
                memcpy(&pck, buf, sizeof(struct arp_pck));
                INFO_PRINT("recv_log %d: fill data is %s", recv_log_count,pck.fill_data);
            }
            recv_log_count++;
        }
    }
    else
    {
        DEBUG_PRINT("your input tap interface name is wrong");
    }
}